#include "Config.h"
#include "Log/Log.h"
#include "Poco/File.h"
#include "Poco/FileStream.h"
#include "Poco/JSON/Parser.h"

Config* Config::m_pInstance = NULL;

Config::Config() : JsonFile(), BaseThread(true)
{
    m_bChange = false;
}

/*Config* Config::Instance()
{
    if (m_pInstance == NULL)
    {
        m_pInstance = new Config();
        if (m_pInstance->Init(CONFIG_FILE) != 0)
        {
            printf("not find file %s\n", CONFIG_FILE);
            exit(-1);
        }
        m_pInstance->m_bChange = m_pInstance->Get("updateConfig");
        if (m_pInstance->m_bChange)
        {
            m_pInstance->SetEvent();
        }
    }
    return m_pInstance;
}*/

int Config::SingleStep()
{
    if (m_bChange)
    {
        SaveToFile();
        m_bChange = false;
    }
    return 3 * 1000;
}

int Config::Set(std::string strKey, Poco::Dynamic::Var var)
{
    int iSet = JsonFile::Set(strKey, var);
    if (iSet == 0)
    {
        m_bChange = true;
        SetEvent();
    }
    return 0;
}

int Config::Add(std::string strKey, Poco::Dynamic::Var var)
{
    int iAdd = JsonFile::Add(strKey, var);
    if (iAdd == 0)
    {
        m_bChange = true;
        SetEvent();
    }
    return 0;
}

int Config::Del(std::string strKey)
{
    int iDel = JsonFile::Del(strKey);
    if (iDel == 0)
    {
        m_bChange = true;
        SetEvent();
    }
    return 0;
}

ConfigManager* ConfigManager::m_pInstance = NULL;

ConfigManager* ConfigManager::Instance()
{
    if (m_pInstance == NULL)
    {
        m_pInstance = new ConfigManager();
    }
    return m_pInstance;
}

Config* ConfigManager::GetConfig(std::string strName)
{
    if (m_mapConfig.find(strName) != m_mapConfig.end())
    {
        return m_mapConfig[strName];
    }
    else
    {
        Config* pConfig = new Config();
        if (pConfig->Init(strName) == 0)
        {
            m_mapConfig[strName] = pConfig;
            return pConfig;
        }
        else
        {
            delete pConfig;
            return NULL;
        }
    }
}

ConfigManager::~ConfigManager()
{
    for (auto it = m_mapConfig.begin(); it != m_mapConfig.end(); it++)
    {
        delete it->second;
    }
    m_mapConfig.clear();
}
